// pages/favorites/favorites.js
Page({
  data: {
    // 收藏的餐厅列表
    favoriteRestaurants: [],
    // 是否暗黑模式
    isDarkMode: false
  },

  onLoad() {
    // 从本地存储获取收藏的餐厅
    this.loadFavorites();
    // 检查暗黑模式
    this.checkDarkMode();
  },

  // 加载收藏的餐厅
  loadFavorites() {
    const favorites = wx.getStorageSync('favoriteRestaurants') || [];
    this.setData({
      favoriteRestaurants: favorites
    });
  },

  // 检查暗黑模式
  checkDarkMode() {
    const systemInfo = wx.getSystemInfoSync();
    const isDarkMode = systemInfo.theme === 'dark';
    this.setData({ isDarkMode });
  },

  // 取消收藏
  toggleCollect(e) {
    const id = e.currentTarget.dataset.id;
    const favorites = this.data.favoriteRestaurants.filter(item => item.id !== id);
    
    this.setData({
      favoriteRestaurants: favorites
    });

    // 更新本地存储
    wx.setStorageSync('favoriteRestaurants', favorites);

    wx.showToast({
      title: '取消收藏',
      icon: 'success'
    });
  },

  // 分享餐厅
  shareRestaurant(e) {
    const item = e.currentTarget.dataset.item;
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  // 返回首页
  goBack() {
    wx.navigateBack();
  },

  onShareAppMessage(e) {
    const item = e.target.dataset.item;
    return {
      title: `推荐餐厅：${item.name}`,
      path: '/pages/home/home',
      imageUrl: item.photos?.[0]?.url || '/images/empty-icon.png'
    };
  },

  // 图片加载失败处理
  onImageError(e) {
    const id = e.currentTarget.dataset.id;
    const restaurants = this.data.favoriteRestaurants;
    const index = restaurants.findIndex(item => item.id === id);
    
    if (index !== -1) {
      // 设置默认图片
      restaurants[index].photos = [{ url: '/images/empty-icon.png' }];
      this.setData({
        favoriteRestaurants: restaurants
      });
    }
  }
})